/* 
  1 翻转链表
  1 -> 2 -> 3 -> 4 -> 5
  5 -> 4 -> 3 -> 2 -> 1
*/

// 1 非递归实现
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function (head) {
  let prev = null;
  let curr = head;
  while (curr) {
    let next = curr.next;
    curr.next = prev;
    prev = curr;
    curr = next;
  }
  return prev;
};

// 递归实现

// 宏观语义：就是翻转以head为头指针的链表，并返回翻转后的头指针
var reverseList = function (head) {
  if (!head || !head.next) {
    return head; // 不需要翻转
  }
  const rev = reverseList(head.next); // 翻转以head.next为头结点的链表
  /* 
    这里是最经典的问题，在翻转链表后，怎么将链表的尾节点的next指向head?
    这里刚好head.next就是存放这个尾节点，所以有：head.next.next = head;
  */
  head.next.next = head;
  head.next = null;
  return rev; // 返回翻转完成后的头指针
};
